import os

from alipay import AliPay
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
from django.http import HttpResponseForbidden
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.models import OrderInfo
from payment.models import Payment


class PaymentView(APIView):
    def get(self, request):
        # 生成支付链接
        # 1, 接收数据
        order_id = request.query_params.get('order_id')

        # 2, 校验数据
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 9999, 'errmsg': '订单号不正确'})

        # 3, 处理业务
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string

        # 4, 返回响应
        res = {
            'code': 0,
            'errmsg': '成功',
            'alipay_url': alipay_url
        }
        return JsonResponse(res)

        pass


class PaymentStatusView(APIView):
    def get(self, request):
        # 接收支付结果, 并校验保存结果
        """
        http://127.0.0.1:8080/payment/status/?
        charset=utf-8
        &out_trade_no=20201112021243000000024   # 我们的订单id
        &method=alipay.trade.page.pay.return
        &total_amount=13197.00  # 总金额
        &sign=U4ikCOik994RPkAF7ACAHFBOw4mdbRIhSjk%2BiqEtwFVNXQQD9p0DttYSOp4hMtYt%2B%2BR5QJZbaW129%2BzkpZYLAXd8r4UXYC2zSOiuVoFJa8knCyF1uwdIaQVxa3p%2B5Ja608C4IEYFcLEqT2qNuKy9W6A1FbtK1wOhPBY1cBPgb%2FYkOA21xUXdws%2BOmmpN5PDpMjJOl8ynk9b16BhtlhTzrURJtZcDJ4ME%2F55nW2rC6LYERY%2Bb8RBj1LGx0Ix%2Biua68wR9St9pYTuIP3vCA3Sa53Uz%2FKToUG4rjYd5%2FeAfAZIdjb72VTr8ILoRkHGd0FDzzUPpjL639gXZCjjQ%2BahuNA%3D%3D   # 签名
        &trade_no=2020111222001494010500863162   # 支付宝的交易号
        &auth_app_id=2016080100142469   # 我们的沙箱appid
        &version=1.0   # 接口的版本
        &app_id=2016080100142469  # 我们的沙箱appid
        &sign_type=RSA2  # 非对称加密
        &seller_id=2088102169475485   # 付款人
        &timestamp=2020-11-12%2011%3A28%3A03  # 交易时间戳
        """
        # 1, 接收数据
        data = request.query_params.dict()
        sign = data.pop('sign')

        # 2, 校验数据

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data, sign)

        if not success:
            return Response({'code':999, 'msg':'非法请求'})

        # 3, 处理业务
        # 保存一下 美多订单号 和 支付宝支付编号
        order = OrderInfo.objects.get(order_id=data['out_trade_no'])
        trade_id = data['trade_no']

        # order 的状态 必须是 未支付状态
        if order.status != OrderInfo.ORDER_STATUS_ENUM['UNPAID']:
            return Response({'code':999, 'msg':'订单状态不正确'})

        # payment 订单关系表中, 没有  trade_id
        count = Payment.objects.filter(trade_id=trade_id).count()
        if count > 0:
            return Response({'code':999, 'msg':'订单已处理'})

        Payment.objects.create(
            order=order,
            trade_id=trade_id
        )
        # 修改订单状态
        order.status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        order.save()

        # 4, 返回响应
        context = {
            'code': 0,
            'msg': '订单支付成功!',
            'order_id': order.order_id
        }
        return Response(context)
